<?php
// +----------------------------------------------------------------------
// | 幕小铺
// +----------------------------------------------------------------------
// | 版权所有 2016~2020 幕小铺科技（大连）有限公司
// +----------------------------------------------------------------------
// | 2020/06/02
// +----------------------------------------------------------------------

namespace app\erp\admin;

use app\admin\controller\Admin;
use think\Db;
use app\common\builder\ZBuilder;
use think\facade\Cache;
/**
 * 团购管理
 * @package app\cms\admin
 */
class GroupSponsor extends Admin
{
    /**
     * 首页
     * @author  dou<51779987@qq.com>
     * @return mixed
     */
    public function index()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);
        //获取筛选
        $map = $this->getMap();
        //数据获取
        $data = input();
        //tab
        $list_tab = [
            'tab4' => ['title' => '全部团购', 'url' => url('index', ['group' => 'tab4'])],
            'tab1' => ['title' => '进行中', 'url' => url('index', ['group' => 'tab1'])],
            'tab2' => ['title' => '已结束', 'url' => url('index', ['group' => 'tab2'])],
            'tab3' => ['title' => '已禁用', 'url' => url('index', ['group' => 'tab3'])],
        ];

        // 数据列表[进行中/结束/禁用/全部/]
        $group = isset($data['group']) ? $data['group'] : 'tab4';
        switch ($group) {
            case 'tab1':
                $map[] = ['tg_start_time', '<=', time()];
                $map[] = ['tg_end_time', '>=', time()];
                $map[] = ['tg_status', '>', 0];
                break;
            case 'tab2':
                $map[] = ['tg_end_time', '<', time()];
                $map[] = ['tg_status', '>', 0];
                break;
            case 'tab3':
                $map[] = ['tg_status', '=', 0];
                break;
            default:
                break;
        }

        //数据列表
        $data_list = model('ErpGroupSponsor', 'model') -> where($map) -> order('tg_status desc,create_time desc') -> paginate();

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('团购管理') // 设置页面标题
            ->setPrimaryKey('id') // 设置主键名为id
            ->setTableName('erp_group_sponsor') // 设置数据表名
            ->addColumns([ // 批量添加列
                // ['__INDEX__', '序号'],
                ['id', '团购ID'],
                ['tg_title', '团购标题'],
                //['tg_join_num', '参团人数'],
                ['tg_start_time', '团购开始时间', 'datetime'],
                ['tg_end_time', '结束时间', 'datetime'],
                ['update_time', '创建时间', 'datetime'],
                ['tg_status', '启用', 'switch'],
                ['right_button', '操作', 'btn']
            ])
            ->setSearchArea([
                ['text', 'id', '团购ID'],
                ['text', 'tg_title', '团购标题', 'like'],
                ['daterange', 'update_time', '创建时间'],
            ])
            ->setTabNav($list_tab,  $group)
            ->addTopButton('add', '', ['area' => ['50%', '80%']])
            ->addRightButton('custom', ['title' => '参与活动商品', 'href' => url('erp/group_sponsor/details', ['id' => '__id__'])])
            ->addRightButton('edit','', ['area' => ['50%', '80%']]) // 批量添加右侧按钮
            ->addRightButton('delete') // 批量添加右侧按钮
            ->setRowList($data_list) // 设置表格数据
            ->fetch(); // 渲染页面
    }

    /**
     * 添加-(旧版)
     * 创建团购单同时选择商品--利用缓存
     * @author  dou<51779987@qq.com>
     * @return mixed
     * @throws \think\Exception
     */
    public function add_jiu($time_str=''){
        if ($this->request->isPost()) {
            //数据接收
            $data = $this->request->post('', null, 'trim');
            $url_json['tg_title']              = strval(isset($data['tg_title']) ? $data['tg_title'] : '');
            $url_json['tg_join_num']           = intval(isset($data['tg_join_num']) ? $data['tg_join_num'] : 0);
            $url_json['tg_start_time']         = intval(isset($data['tg_start_time']) ? strtotime($data['tg_start_time']) : 0);
            $url_json['tg_end_time']           = intval(isset($data['tg_end_time']) ? strtotime($data['tg_end_time']) : 0);
            $url_json['tg_status']             = intval(isset($data['tg_status']) ? $data['tg_status'] : 1);

            //数据验证
            $Validate = validate('GroupSponsor', 'validate');
            if( !$Validate -> scene('group_sponsor_add') -> check($data) ){
                $this->error($Validate -> getError());
            }
            //写入缓存中,上一步在提交时清空原有缓存
            if(!empty($time_str)){
                Cache::rm('group_sponsor'.'_'.$time_str);
                Cache::rm('sku_linshi'.'_'.$time_str);
            }
            $time_str = time();
            Cache::set('group_sponsor'.'_'.$time_str,[ $time_str =>$url_json ],3600);
            if(!empty(Cache::get('group_sponsor'.'_'.$time_str))){
                $this->redirect('add_goods',['time_str'=>$time_str]);
            }else{
                $this->error('未知原因，请重新填写表单');
            }
        }
        $map = [];
        $uid = UID;//后台管理员ID
        $sotre_user = model('app\user\model\User') -> find($uid);//获取列表

        if($sotre_user['store_uid'] > 0){
            //根据门店id 查询出仓库的id
            $warehouse_list = model('ErpStoreWarehouse') -> getStoreWarehouse($sotre_user['store_id']);
            foreach ($warehouse_list['data'] as $key => $value) {
                if($value['type'] == 1){//分店仓库
                    $store_warehouse_list[] = $value['wid'];
                }
            }
            $warehouse_id = $store_warehouse_list[0];
            $map[] = ['id', '=', $warehouse_id];
        }
        $warehouse_id = model('ErpWarehouse') -> where($map) -> column('id,title');
        //返回上一步时通过缓存获取数据
        $history_arr = Cache::get('group_sponsor'.'_'.$time_str);
        if(!empty($history_arr) && is_array($history_arr)){
            $history = $history_arr[$time_str];
            $history['tg_start_time'] = date('Y-m-d H:i:s',$history['tg_start_time']);
            $history['tg_end_time'] = date('Y-m-d H:i:s',$history['tg_end_time']);
        }else{
            $history = [];
        }
        // 使用ZBuilder快速创建表单
        $btn = "window.location.href = '".url('erp/group_sponsor/index')."'";
        return ZBuilder::make('form')
            ->setPageTitle('新增团购') // 设置页面标题
            ->addFormItems([ // 批量添加表单项
                ['text', 'tg_title', '团购标题','必填'],
                ['number', 'tg_join_num', '参团人数', '请输入参团人数',1],
                ['daterange', 'tg_start_time,tg_end_time', '团购时间', '团购开始时间&团购结束时间'],
                ['radio','tg_status', '状态', '', [0 => '禁用', 1 => '启用'], 1]
            ])
            ->addText('sort', '排序', '', 100)
            ->setFormData($history)
            ->setBtnTitle(['submit' => '下一步'])
            ->hideBtn(['back'])
            ->addBtn('<button type="button"  onclick = "'.$btn.'" class="btn btn-default">返回列表</button>')
            ->isAjax(false)
            ->fetch();
    }

    /**
     * 添加-商品数量
     * @author  dou<51779987@qq.com>
     * @return mixed
     * @throws \think\Exception
     */
    public function add_goods_jiu($time_str=''){
        if ($this->request->isPost()) {
            $sku_id = input('post.ids/a');
            $ids = implode(',', $sku_id);
            $this -> add_goods_sku(input('time_str'),$ids);
        }
        //获取筛选
        $map = $this->getMap();
        $map = [];
        $goods_id = model('ErpGoods') -> where($map) -> column('id');

        $sku_linshi = Cache::get('sku_linshi'.'_'.$time_str);
        if(!empty($sku_linshi) && is_array($sku_linshi)){
            foreach ($sku_linshi as $key=>$value){
                foreach ($value as $k=>$v){
                    $sku_id_param[] = $v['sku_id'];
                }
            }
            $sku_id_str = implode(',',$sku_id_param);
            $map[] = ['id', 'not in', $sku_id_str];
        }
        $perv = [
            'title' => '上一步',
            'class' => 'btn btn-info',
            'href'  => url('add',['time_str'=>$time_str])
        ];
        $add_goods_sku = [
            'title' => '新增',
            'class' => 'btn btn-primary ajax-post',
            'href'  => url('add_goods',['time_str'=>$time_str])
        ];
        $sku_see = [
            'title' => '已选择商品',
            'class' => 'btn btn-success',
            'href'  => url('add_goods_num',['time_str'=>$time_str])
        ];
        $notid = [];
        $map[] = ['goods_id', 'in', $goods_id];
        $map[] = ['sku_status', '=', 1];
        $data_list = model('ErpGoodsSku') -> where($map) -> order('create_time desc') -> paginate();//获取列表

        $sku_submit = [
            'title' => '新增',
            'icon'  => 'fa fa-fw fa-key',
            'class' => 'btn btn-xs btn-primary ajax-get',
            'href'  => url('add_goods_sku', ['time_str'=>$time_str,'ids' => '__id__']),
        ];

        return ZBuilder::make('table') // 设置页面标题
        ->setPageTitle('商品列表')
            ->setPrimaryKey('id') // 设置主键名为id
            ->setTableName('erp_goods_sku') // 设置数据表名
            ->addColumns([ // 批量添加列
                ['id', '规格id'],
                ['goods_name', '商品名称'],
                ['goods_specifications', '规格'],
                ['purchase_price', '进货价格'],
                ['right_button', '操作', 'btn']
            ])
            ->setSearch(['goods_name' => '商品名', 'goods_specifications' => '单品名称']) // 设置搜索参数
            ->addTopButton('custom', $perv) // 添加授权按钮
            ->addTopButton('custom', $add_goods_sku) // 添加授权按钮
            ->addTopButton('custom', $sku_see, true) // 添加授权按钮
            ->addRightButton('sku_submit', $sku_submit) // 批量添加右侧按钮
            ->setRowList($data_list) // 设置表格数据
            ->fetch(); // 渲染页面
    }

    /**
     * 编辑
     * @param null $id 团购单id
     * @author dou <51779987@qq.com>
     * @return mixed
     * @throws \think\Exception
     */
    public function edit_jiu($id = null,$time_str='')
    {
        if ($id === null) $this->error('缺少参数');
        //获取表数据
        $history_arr = Cache::get('group_sponsor'.'_'.$time_str);
        if(!empty($history_arr) && is_array($history_arr)) {
            $info = $history_arr[$time_str];
        }else{
            $info = model('ErpGroupSponsor')->find($id);
        }
        // 保存数据
        if ($this->request->isPost()) {
            //数据接收
            $data = $this->request->post('', null, 'trim');
            $url_json['tg_title']              = strval(isset($data['tg_title']) ? $data['tg_title'] : '');
            $url_json['tg_join_num']           = intval(isset($data['tg_join_num']) ? $data['tg_join_num'] : 0);
            $url_json['tg_start_time']         = intval(isset($data['tg_start_time']) ? strtotime($data['tg_start_time']) : 0);
            $url_json['tg_end_time']           = intval(isset($data['tg_end_time']) ? strtotime($data['tg_end_time']) : 0);
            $url_json['tg_status']             = intval(isset($data['tg_status']) ? $data['tg_status'] : 1);

            //数据验证
            $Validate = validate('GroupSponsor', 'validate');
            if( !$Validate -> scene('group_sponsor_add') -> check($data) ){
                $this->error($Validate -> getError());
            }
            //写入缓存中,上一步在提交时清空原有缓存
            if(!empty($time_str)){
                Cache::rm('group_sponsor'.'_'.$time_str);
                Cache::rm('sku_linshi'.'_'.$time_str);
            }
            $time_str = time();
            Cache::set('group_sponsor'.'_'.$time_str,[ $time_str =>$url_json ],3600);
            if(!empty(Cache::get('group_sponsor'.'_'.$time_str))){
                $this->redirect('edit_goods',['time_str'=>$time_str,'id'=>$data['id']]);
            }else{
                $this->error('未知原因，请重新填写表单');
            }
        }
        $map = [];
        $uid = UID;//后台管理员ID
        $sotre_user = model('app\user\model\User') -> find($uid);//获取列表

        if($sotre_user['store_uid'] > 0){
            //根据门店id 查询出仓库的id
            $warehouse_list = model('ErpStoreWarehouse') -> getStoreWarehouse($sotre_user['store_id']);
            foreach ($warehouse_list['data'] as $key => $value) {
                if($value['type'] == 1){//分店仓库
                    $store_warehouse_list[] = $value['wid'];
                }
            }
            $warehouse_id = $store_warehouse_list[0];
            $map[] = ['id', '=', $warehouse_id];
        }
        $warehouse_id = model('ErpWarehouse') -> where($map) -> column('id,title');
        $info['tg_start_time'] = date('Y-m-d H:i:s',$info['tg_start_time']);
        $info['tg_end_time'] = date('Y-m-d H:i:s',$info['tg_end_time']);
        // 使用ZBuilder快速创建表单

        $btn = "window.location.href = '".url('erp/group_sponsor/index')."'";
        return ZBuilder::make('form')
            ->setPageTitle('新增团购') // 设置页面标题
            ->addFormItems([ // 批量添加表单项
                ['text', 'tg_title', '团购标题','必填'],
                ['number', 'tg_join_num', '参团人数', '请输入参团人数',1],
                ['daterange', 'tg_start_time,tg_end_time', '团购时间', '团购开始时间&团购结束时间'],
                ['radio','tg_status', '状态', '', [0 => '禁用', 1 => '启用'], 1]
            ])
            ->addHidden('id',$id)
            ->addText('sort', '排序', '', 100)
            ->setFormData($info)
            ->setBtnTitle(['submit' => '下一步'])
            ->hideBtn(['back'])
            ->addBtn('<button type="button"  onclick = "'.$btn.'" class="btn btn-default">返回列表</button>')
            ->isAjax(false)
            ->fetch();
    }

    /**
     * 编辑-商品数量
     * @author  dou<51779987@qq.com>
     * @return mixed
     * @throws \think\Exception
     */
    public function edit_goods_jiu($time_str='',$id=''){
        if ($this->request->isPost()) {
            $sku_id = input('post.ids/a');
            $ids = implode(',', $sku_id);
            $this -> add_goods_sku(input('time_str'),$ids);
        }
        //获取sku表数据
        $sku_data = model('ErpGroupSponsorSku')->where('group_sid','=',$id)->column('sku_id');
        $sku_linshi = Cache::get('sku_linshi'.'_'.$time_str);
        if(!empty($sku_linshi) && is_array($sku_linshi)){
            foreach ($sku_linshi as $key=>$value){
                foreach ($value as $k=>$v){
                    $sku_id_param[] = $v['sku_id'];
                }
            }
            if(!empty($sku_id_param) && is_array($sku_id_param) && !empty($sku_data) && is_array($sku_data)){
                $sku_data = array_merge($sku_id_param,$sku_data);
            }
        }
        $sku_id_str = implode(',',$sku_data);
        $perv = [
            'title' => '上一步',
            'class' => 'btn btn-info',
            'href'  => url('edit',['time_str'=>$time_str,'id'=>$id])
        ];
        $add_goods_sku = [
            'title' => '新增',
            'class' => 'btn btn-primary ajax-post',
            'href'  => url('add_goods',['time_str'=>$time_str])
        ];
        $sku_see = [
            'title' => '已选择商品',
            'class' => 'btn btn-success',
            'href'  => url('add_goods_num',['time_str'=>$time_str,'id'=>$id])
        ];

        $notid = [];
        //获取筛选--检查缓存
        $map = $this->getMap();
        $map = [];
        $goods_id = model('ErpGoods') -> where($map) -> column('id');

        $map = [];
        $map[] = ['id', 'not in', $sku_id_str];
        $map[] = ['goods_id', 'in', $goods_id];
        $map[] = ['sku_status', '=', 1];
        $data_list = model('ErpGoodsSku') -> where($map) -> order('create_time desc') -> paginate();//获取列表

        $sku_submit = [
            'title' => '新增',
            'icon'  => 'fa fa-fw fa-key',
            'class' => 'btn btn-xs btn-primary ajax-get',
            'href'  => url('add_goods_sku', ['time_str'=>$time_str,'ids' => '__id__']),
        ];

        return ZBuilder::make('table') // 设置页面标题
        ->setPageTitle('商品列表')
            ->setPrimaryKey('id') // 设置主键名为id
            ->setTableName('erp_goods_sku') // 设置数据表名
            ->addColumns([ // 批量添加列
                ['id', '规格id'],
                ['goods_name', '商品名称'],
                ['goods_specifications', '规格'],
                ['purchase_price', '进货价格'],
                ['right_button', '操作', 'btn']
            ])
            ->setSearch(['goods_name' => '商品名', 'goods_specifications' => '单品名称']) // 设置搜索参数
            ->addTopButton('custom', $perv) // 添加授权按钮
            ->addTopButton('custom', $add_goods_sku) // 添加授权按钮
            ->addTopButton('custom', $sku_see, true) // 添加授权按钮
            ->addRightButton('sku_submit', $sku_submit) // 批量添加右侧按钮
            ->setRowList($data_list) // 设置表格数据
            ->fetch(); // 渲染页面
    }

    /**
     * 添加-商品sku[添加&编辑公用]
     * @author  dou<51779987@qq.com>
     * @return mixed
     * @throws \think\Exception
     */
    public function add_goods_sku_jiu($time_str,$ids = []){
        $sku_id = explode(',', $ids);
        //插入单品
        $list = $sku_linshi = Cache::get('sku_linshi'.'_'.$time_str);
        foreach($sku_id as $sku_id){
            $sku_info = model('ErpGoodsSku') -> find($sku_id);//获取列表
            if(isset($sku_linshi[$time_str])  && !empty($sku_linshi[$time_str]) && is_array($sku_linshi[$time_str])){
                foreach ($sku_linshi as $ksku=>$vsku){
                    if(!in_array($sku_id,$vsku)){
                        $list[$time_str][] = ['goods_id' => $sku_info['goods_id'],'sku_id' => $sku_id, 'purchase_price' => $sku_info['purchase_price'],'inventory' => $sku_info['inventory']];
                    }
                }
            }else{
                $list[$time_str][] = ['goods_id' => $sku_info['goods_id'],'sku_id' => $sku_id, 'purchase_price' => $sku_info['purchase_price'],'inventory' => $sku_info['inventory']];
            }
        }
        Cache::set('sku_linshi'.'_'.$time_str,$list,3600);
        $this->success('新增成功');
    }

    /**
     * 商品详细编辑-后提交[添加&编辑公用，根据$id判断]
     * @author  dou<51779987@qq.com>
     * @return mixed
     * @throws \think\Exception
     */
    public function add_goods_num_jiu($time_str='',$id=''){
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $sku_info = [];
            if(!empty($data)){
                unset($data['__token__']);
                foreach ($data as $key=>$value){
                    $params = explode('/',$key);
                    $sku_info[$params[1]][$params[0]] = $value;
                }
            }

            //数据验证
            foreach ($sku_info as $kv=>$vv){
                    if(!empty($id)){
                        $is_use = model('ErpGroupSponsorSku')->find($vv['id']);
                        //当禁用是，检查已使用的数量，已使用的sku无法禁用
                        if($vv['sp_status'] < 1){
                            if(!empty($is_use) && !is_null($is_use['ksy_num'])){
                                if($is_use['ksy_num'] < $is_use['sum_num']){
                                    $this->error('该商品已参与团购活动，不可禁用！');
                                }
                            }
                        }
                        //团购总库存必出大于等于可使用数量
                        if(!empty($is_use) && !is_null($is_use['ksy_num'])){
                            $num = $vv['sum_num'] - ($is_use['sum_num'] - $is_use['ksy_num']);
                            if($num < 0){
                                $this->error('参与团购总库存数必须大于等于'.($is_use['sum_num'] - $is_use['ksy_num']).'个');
                            }else{
                                $sku_info[$kv]['ksy_num'] = $num;
                            }
                        }else{
                            $sku_info[$kv]['ksy_num'] = $vv['sum_num'];
                        }
                        $Validate = validate('GroupSponsor', 'validate');
                        if( !$Validate -> scene('group_sponsor_edit_sku') -> check($vv) ){
                            $this->error($Validate -> getError());
                        }
                    }else{
                        $Validate = validate('GroupSponsor', 'validate');
                        if( !$Validate -> scene('group_sponsor_add_sku') -> check($vv) ){
                            $this->error($Validate -> getError());
                        }
                    }
            }
            if(!empty($sku_info)){
                //获取数据并存表
                $group_sponsor  = Cache::get('group_sponsor'.'_'.$time_str);
                $user_id        = isset($group_sponsor[$time_str]['user_id'])?$group_sponsor[$time_str]['user_id']:1;
                $tg_title       = isset($group_sponsor[$time_str]['tg_title'])?$group_sponsor[$time_str]['tg_title']:'';
                $tg_join_num    = isset($group_sponsor[$time_str]['tg_join_num'])?$group_sponsor[$time_str]['tg_join_num']:'';
                $tg_status      = isset($group_sponsor[$time_str]['tg_status'])?$group_sponsor[$time_str]['tg_status']:'';
                $tg_start_time  = isset($group_sponsor[$time_str]['tg_start_time'])?$group_sponsor[$time_str]['tg_start_time']:'';
                $tg_end_time    = isset($group_sponsor[$time_str]['tg_end_time'])?$group_sponsor[$time_str]['tg_end_time']:'';
                if(!empty($id)){
                    $rel = controller('GroupSponsorlogic', 'logic') -> edit($user_id, $id, $tg_title, $tg_join_num, $tg_status, $tg_start_time, $tg_end_time, $sku_info);
                    $mag = '编辑成功';
                }else{
                    $rel = controller('GroupSponsorlogic', 'logic') -> add($user_id, $tg_title, $tg_join_num, $tg_status, $tg_start_time, $tg_end_time, $sku_info);
                    $mag = '新增成功';
                }

                if($rel['code'] > 0){
                    //成功后清空缓存
                    Cache::rm('group_sponsor'.'_'.$time_str);
                    Cache::rm('sku_linshi'.'_'.$time_str);
                    $this->success($mag, 'erp/group_sponsor/index', '_parent_reload');
                }else{
                    $this->error($rel['message']);
                }
            }
        }
        //读取缓存数据
        $data_list_linshi = Cache::get('sku_linshi'.'_'.$time_str);
        //查找表数据
        $sku_data = model('ErpGroupSponsorSku')->where('group_sid','=',$id)->column('*');
        if(!empty($data_list_linshi) && is_array($data_list_linshi) && !empty($sku_data) && is_array($sku_data)){
            $data_list_arr = array_merge($data_list_linshi[$time_str],$sku_data);
            $data_list[$time_str] = $data_list_arr;
        }else{
            if(!empty($data_list_linshi) && is_array($data_list_linshi)){
                $data_list = $data_list_linshi;
            }elseif (!empty($sku_data) && is_array($sku_data)){
                $data_list[$time_str] = $sku_data;
            }else{
                $data_list[$time_str] = [];
            }
        }

        $table_data = [
            ['规格id', '商品名称', '规格名', '进货价格','库存数量', '','参与团购总库存数','已使用库存数量', '展示价格','购买次数限制','限购数量','排序', '禁用'],
        ];
        if(!empty($data_list[$time_str])){
            foreach($data_list[$time_str] as $key => $value){
                $sku_info = model('ErpGoodsSku') -> find($value['sku_id']);//获取列表
                $data_list[$time_str][$key]['goods_name'] 				= $sku_info['goods_name'];
                $data_list[$time_str][$key]['goods_specifications'] 	= $sku_info['goods_specifications'];
                $data_list[$time_str][$key]['purchase_price'] 			= $sku_info['purchase_price'];
                $data_list[$time_str][$key]['inventory'] 				= $sku_info['inventory'];
            };
            foreach($data_list[$time_str] as $key => $value){
                if(isset($value['sp_status'])){
                    if($value['sp_status']==1){
                        $select = '<select name="sp_status/'. $value['sku_id'] .'" /><option value="1" selected>可用</option><option value="0">禁用</option></select>';
                    }else{
                        $select = '<select style="color: red" name="sp_status/'. $value['sku_id'] .'" /><option value="1">可用</option><option value="0" selected>禁用</option></select>';
                    }
                }else{
                    $select = '<select name="sp_status/'. $value['sku_id'] .'" /><option value="1" selected>可用</option><option value="0">禁用</option></select>';
                }
                if(!empty($value['ksy_num'])){
                    $value['ksy_num'] = $value['sum_num'] - $value['ksy_num'];
                }else{
                    $value['ksy_num'] = 0;
                }

                $table_data[] = [
                    $value['sku_id'],
                    $value['goods_name'],
                    $value['goods_specifications'],
                    $value['purchase_price'],
                    $value['inventory'],
                    '<input type="hidden" name="id/'. $value['sku_id'] .'" value="'.@$value['id'].'"/>',
                    '<input type="text" name="sum_num/'. $value['sku_id'] .'" value="'.@$value['sum_num'].'"/>',
                    $value['ksy_num'],
                    '<input type="text" name="show_price/'. $value['sku_id'] .'" value="'.@$value['show_price'].'"/>',
                    '<input type="text" name="tries/'. $value['sku_id'] .'" value="'.@$value['tries'].'"/>',
                    '<input type="text" name="limit_num/'. $value['sku_id'] .'" value="'.@$value['limit_num'].'"/>',
                    '<input type="text" name="sorts/'. $value['sku_id'] .'" value="'.(@$value['sorts']?:100).'"/>',
                    $select,
                ];
            }
        }


        return ZBuilder::make('form')
            ->setPageTitle('团购商品添加') // 设置页面标题
            ->addFormItems([])
            ->setFormData($data_list[$time_str]) // 设置表单数据
            ->addFormItems([ // 批量添加表单项
                ['complexTable', 'list_user', '团购商品sku', $table_data]
            ])
            ->fetch();
    }

    /**
     * 详细
     * @param null $id 团购id
     * @author dou <51779987@qq.com>
     * @return mixed
     * @throws \think\Exception
     */
    public function details($id = []){
        if ($id === null) $this->error('缺少参数');
        $info = model('ErpGroupSponsorSku', 'model')  -> where('group_sid','=',$id) -> order('sp_status desc,sorts asc,create_time desc') -> paginate();
        foreach ($info as $k=>$value){
            $sku_info =  model('ErpGoodsSku')->field('goods_name,goods_specifications') -> find($value['sku_id']);
            $info[$k]['goods_name'] = $sku_info['goods_name'];
            $info[$k]['goods_specifications'] = $sku_info['goods_specifications'];
            //门店名称
            $store_arr = model('ErpStore')->where('id','=',$value['store_id'])->order('create_time asc') -> column('title');
            if(isset($store_arr[0]) && !empty($store_arr[0])){
                $info[$k]['store'] = $store_arr[0];
            }else{
                $info[$k]['store'] = '暂无';
            }
            //门店下仓库库存数
            $store_sku_info = $this->get_sku_info($value['store_id'],$value['sku_id']);
            if(isset($store_sku_info) && !empty($store_sku_info)){
                $info[$k]['available_num'] = $store_sku_info;
            }else{
                $info[$k]['available_num'] = '暂无';
            }
        }
        // 使用ZBuilder快速创建表单
        return ZBuilder::make('table')
            ->setPageTitle('团购商品sku展示') // 设置页面标题
            ->setPrimaryKey('id') // 设置主键名为id
            ->setTableName('erp_coupon_useinfo') // 设置数据表名
            ->addColumns([ // 批量添加列
                // ['__INDEX__', '序号'],
                ['sp_status', '状态', 'status', '', [0=>'禁用:danger',1 => '可用:success']],
                //['id', '团购id'],
                ['store', '门店名称', 'text'],
                ['goods_name', '参与商品名称', 'text'],
                ['goods_specifications', '参与商品规格', 'text'],
                //['nick_name', '使用人', 'link', url('user_center/index/details', ['uid' => '__coupon_user__']), '_blank', 'pop'],
                ['show_price', '展示价格', 'text'],
               /* ['limit_num', '限购数量', 'text'],
                ['tries', '购买次数限制', 'text'],*/
                ['available_num', '门店总库存数', 'text'],
                ['sum_num', '参团库存数', 'text'],
                ['dj_num', '冻结库存数', 'text'],
                ['ksy_num', '可用库存数', 'text'],
                ['update_time', '发布时间','datetime'],
                ['sorts', '排序','text'],
                ['right_button', '操作', 'btn']
            ])
            ->addTopButton('custom', ['title' => '返回团购列表', 'href' => url('erp/group_sponsor/index')])
            ->addTopButton('custom', ['title' => '添加参购商品', 'href' => url('erp/group_sponsor/add_goods', ['id' => $id])],true)
            ->addRightButton('custom', ['title' => '编辑', 'href' => url('erp/group_sponsor/edit_goods', ['id' => '__id__'])],true)
            ->addRightButton('custom', ['title' => '参与团购人员名单', 'href' => url('erp/group_sponsor/buyers', ['id' => $id,'sku_id' => '__id__'])],true)
            ->setRowList($info) // 设置表格数据
            ->fetch(); // 渲染页面
    }

    /**
     * 删除
     */
    public function delete($ids = []){
        $info = model('ErpGroupSponsor') -> where('id', $ids) -> find();
        $info_sku = model('ErpGroupSponsorSku') -> where('group_sid', $ids) -> column('*');
        //当禁用是，检查已使用的数量，已使用的sku无法禁用
        if(!empty($info)){
            if(!empty($info_sku)){
                foreach ($info_sku as $key=>$value){
                    if(!empty($value) && !is_null($value['ksy_num'])){
                        if($value['ksy_num'] < $value['sum_num']){
                            $this->error('该团购中部分商品已经参与活动，不可删除！');
                        }
                    }
                    $ids_sku[] = $value['id'];
                }
            }
            $rel = model('ErpGroupSponsor') -> deleteData($ids);
            if(!empty($ids_sku) && is_array($ids_sku)){
                foreach ($ids_sku as $vids){
                    $rel = model('ErpGroupSponsorSku') -> deleteData($vids);
                }
            }
            $map = [];
            foreach ($info_sku as $v){
                $map['group_sid'] = $v['group_sid'];
                $map['sku_id'] = $v['sku_id'];
                $rel_d = model('ErpGroupSponsorSkuImgs') -> where($map) -> delete();
            }
        }
        $this->success('删除成功');
    }


    /**
     * 添加-团购单(二版-新)
     * 先创建团购单，后通过列表中进行商品的添加。
     * time:2020-10-13   13:40
     */
    /**
     * 添加
     * @author  dou<51779987@qq.com>
     * @return mixed
     * @throws \think\Exception
     */
    public function add($time_str=''){
        if ($this->request->isPost()) {
            //数据接收
            $data = $this->request->post('', null, 'trim');
            $tg_title              = strval(isset($data['tg_title']) ? $data['tg_title'] : '');
            $tg_join_num           = intval(isset($data['tg_join_num']) ? $data['tg_join_num'] : 0);
            $tg_start_time         = intval(isset($data['tg_start_time']) ? strtotime($data['tg_start_time']) : 0);
            $tg_end_time           = intval(isset($data['tg_end_time']) ? strtotime($data['tg_end_time']) : 0);
            $tg_status             = intval(isset($data['tg_status']) ? $data['tg_status'] : 1);

            if($tg_end_time < $tg_start_time){
                $this->error('结束时间不能小于开始时间');
            }

            //数据验证
            $Validate = validate('GroupSponsor', 'validate');
            if( !$Validate -> scene('group_sponsor_add') -> check($data) ){
                $this->error($Validate -> getError());
            }

            $rel = model('ErpGroupSponsor') -> addData($tg_title, $tg_join_num, $tg_status, $tg_start_time, $tg_end_time);
            if($rel['code'] == 200){
                $this->success('新增成功前往列表页添加商品','', '_parent_reload');
            }else{
                $this->error($rel['message']);
            }

        }
        // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->setPageTitle('新增团购') // 设置页面标题
            ->addFormItems([ // 批量添加表单项
                ['text', 'tg_title', '团购标题','必填'],
                //['number', 'tg_join_num', '参团人数', '请输入参团人数',1],
                ['datetime', 'tg_start_time', '团购开始时间', '团购时间'],
                ['datetime', 'tg_end_time', '团购结束时间', '团购时间'],
                ['radio','tg_status', '状态', '', [0 => '禁用', 1 => '启用'], 1]
            ])
            ->addText('sort', '排序', '', 100)
            ->addHidden('tg_join_num',10000)
            ->fetch();
    }

    /**
     * 编辑（新版）
     */
    public function edit($id = null)
    {
        if ($id === null) $this->error('缺少参数');
        //获取表数据
        $info = model('ErpGroupSponsor')->find($id);
        // 保存数据
        if ($this->request->isPost()) {
            //数据接收
            $data = $this->request->post('', null, 'trim');
            $tg_title              = strval(isset($data['tg_title']) ? $data['tg_title'] : '');
            $tg_join_num           = intval(isset($data['tg_join_num']) ? $data['tg_join_num'] : 0);
            $tg_start_time         = intval(isset($data['tg_start_time']) ? strtotime($data['tg_start_time']) : 0);
            $tg_end_time           = intval(isset($data['tg_end_time']) ? strtotime($data['tg_end_time']) : 0);
            $tg_status             = intval(isset($data['tg_status']) ? $data['tg_status'] : 1);

            if($tg_end_time < $tg_start_time){
                $this->error('结束时间不能小于开始时间');
            }
            //数据验证
            $Validate = validate('GroupSponsor', 'validate');
            if( !$Validate -> scene('group_sponsor_add') -> check($data) ){
                $this->error($Validate -> getError());
            }
            $rel = model('ErpGroupSponsor') -> editData($id, $tg_title, $tg_join_num, $tg_status, $tg_start_time, $tg_end_time);
            if($rel['code'] == 200){
                $this->success('编辑成功','', '_parent_reload');
            }else{
                $this->error($rel['message']);
            }
        }
        $info['tg_start_time'] = date('Y-m-d H:i:s',$info['tg_start_time']);
        $info['tg_end_time'] = date('Y-m-d H:i:s',$info['tg_end_time']);
        // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->setPageTitle('编辑团购') // 设置页面标题
            ->addFormItems([ // 批量添加表单项
                ['text', 'tg_title', '团购标题','必填'],
                //['number', 'tg_join_num', '参团人数', '请输入参团人数',1],
                ['datetime', 'tg_start_time', '团购开始时间', '团购时间'],
                ['datetime', 'tg_end_time', '团购结束时间', '团购时间'],
                ['radio','tg_status', '状态', '', [0 => '禁用', 1 => '启用'], 1]
            ])
            ->addHidden('id',$id)
            ->addText('sort', '排序', '', 100)
            ->addHidden('tg_join_num',10000)
            ->setFormData($info)
            ->fetch();
    }

    /**
     * 添加-商品(xin )
     */
    public function add_goods($id=''){
        if ($id === null) $this->error('缺少参数');
        if ($this->request->isPost()) {
            //数据接收
            $data = $this->request->post('', null, 'trim');
            if(!isset($data['pic1'])|| empty($data['pic1'])) $this->error('请上传商品缩略图');
 //           if(!isset($data['pic2'])|| empty($data['pic2'])) $this->error('请上传商品详情图');

            $user_id            = intval(isset($data["user_id"]) ? $data["user_id"] : 1);
            $group_sid          = intval(isset($data['group_sid']) ? $data['group_sid'] : 0);
            $sku_id             = intval(isset($data['sku_id']) ? $data['sku_id'] : 0);
            $show_price         = strval(isset($data['show_price']) ? $data['show_price'] : '');
            $limit_num          = intval(isset($data['limit_num']) ? $data['limit_num'] : 0);
            $sorts              = intval(isset($data['sorts']) ? $data['sorts'] : 100);
            $sp_status          = intval(isset($data['sp_status']) ? $data['sp_status'] : 1);
            $tries              = intval(isset($data['tries']) ? $data['tries'] : 0);
            $sum_num            = intval(isset($data['sum_num']) ? $data['sum_num'] : 0);
            $dj_num             = intval(isset($data['dj_num']) ? $data['dj_num'] : 0);
            $ksy_num            = intval(isset($data['ksy_num']) ? $data['ksy_num'] : $sum_num);
            $store_id           = intval(isset($data['store_id']) ? $data['store_id'] : 0);

            //数据验证
            $Validate = validate('GroupSponsor', 'validate');
            if( !$Validate -> scene('group_sponsor_add_sku') -> check($data) ){
                $this->error($Validate -> getError());
            }
            if($sku_id < 1){
                $this->error('参与团购商品不存在');
            }
            //验证数量   是否不存在   不存在0
            //验证数量   是否不存在   存在最低值
            $available_num = $this->get_sku($store_id,$sku_id,2);
            if($available_num['data'] < $sum_num){
                $this->error('参与团购总库存数超过仓库已有总数,最大参团数为'.$available_num['data']);
            }

            //图片上传阿里云
            $data_list = [];
            if($data['pic1']){
                $pic_arr = explode(',', $data['pic1']);
                foreach ($pic_arr as $key => $value) {
                    if($value != ''  && strpos($value,'groupsponsor/'.$group_sid.'/') ==false){
                        $rel_logo_pic = get_aliyun_pic_path($value,'groupsponsor/'.$group_sid.'/');
                        if($rel_logo_pic['code'] != 200) $this->error('图片上传失败');
                        $img_url  = $rel_logo_pic['data']['info']['url'];
                        //获取本地附件信息
                        $attachment_info = model('admin/Attachment') -> find($value);
                        $data_list[] = [
                            'group_sid' => $group_sid,
                            'type' => 1,
                            'sku_id' => $sku_id,
                            'img_url' => $img_url,
                            'width'	=> $attachment_info['width'],
                            'height'	=> $attachment_info['height'],
                            'create_time' => time(),
                            'update_time' => time(),
                        ];
                    }
                }
            }
            if($data['pic2']){
                $pic_arr = explode(',', $data['pic2']);
                foreach ($pic_arr as $key => $value) {
                    if($value != ''  && strpos($value,'groupsponsor/'.$group_sid.'/') ==false){
                        $rel_logo_pic = get_aliyun_pic_path($value,'groupsponsor/'.$group_sid.'/');
                        if($rel_logo_pic['code'] != 200) $this->error('图片上传失败');
                        $img_url  = $rel_logo_pic['data']['info']['url'];
                        //获取本地附件信息
                        $attachment_info = model('admin/Attachment') -> find($value);
                        $data_list[] = [
                            'group_sid' => $group_sid,
                            'type' => 2,
                            'sku_id' => $sku_id,
                            'img_url' => $img_url,
                            'width'	=> $attachment_info['width'],
                            'height'	=> $attachment_info['height'],
                            'create_time' => time(),
                            'update_time' => time(),
                        ];
                    }
                }
            }

            $rel = controller('GroupSponsorlogic', 'logic') -> add_goods($user_id, $group_sid, $sku_id, $show_price, $limit_num, $sorts, $sp_status, $tries, $sum_num, $dj_num, $ksy_num,$store_id, $data_list);

            if($rel['code'] == 200){
                $this->success('新增成功前往列表页添加商品','', '_parent_reload');
            }else{
                $this->error($rel['message']);
            }
        }
        //选择门店
        $list_store = [];
        $list_store_all = [0=>'全店通用'];
        $list_store_c = model('ErpStore')->order('create_time asc') -> column('id,title');
        $list_store = $list_store_all + $list_store_c;
        return ZBuilder::make('form')
            ->setPageTitle('新增团购商品') // 设置页面标题
            //->addSelect('sku_id', '选择商品' , '选择商品' , $data_list)
            ->addLinkage('store_id', '选择门店', '', $list_store, '', url('get_sku'), 'sku_id')
            ->addSelect('sku_id', '选择商品')
            ->addImages_oss('pic1', '产品缩略图', '', '', '', '', '', ['size' => '500,500'])
            ->addImages_oss('pic2', '产品详情图', '', '', '', '', '', ['size' => '500,500'])
            ->addFormItems([ // 批量添加表单项
                ['text','show_price', '展示价格'],
                //['number','limit_num', '限购数量','',1],
                //['number','tries', '购买次数限制','',1],
                ['text','sum_num', '参与团购总库存数'],
                ['text','sorts', '排序','',100],
                ['radio', 'sp_status', '', '', ['不可用', '可用'], 1]
            ])
            ->addHidden('group_sid',$id)
            ->addHidden('limit_num',1)
            ->addHidden('tries',1)
            ->fetch();
    }


    /**
     * 编辑-商品(xin )
     */
    public function edit_goods($id=''){
        if ($id === null) $this->error('缺少参数');
        //查询
        $info = model('ErpGroupSponsorSku')->find($id);
        if(empty($info)){
            $this->error('未查到数据，请返回重试或者联系网站管理员');
        }else{
            $map1 = $map2 = [];
            $sku_img_1 = $sku_img_2 = [];

            $map1[] = ['group_sid', '=', $info['group_sid']];
            $map1[] = ['group_skuid', '=', $id];
            $map1[] = ['sku_id', '=', $info['sku_id']];
            $map1[] = ['type', '=', 1];
            $sku_img_1 = model('ErpGroupSponsorSkuImgs') -> where($map1) -> column('img_url');

            $map2[] = ['group_sid', '=', $info['group_sid']];
            $map2[] = ['group_skuid', '=', $id];
            $map2[] = ['sku_id', '=', $info['sku_id']];
            $map2[] = ['type', '=', 2];
            $sku_img_2 = model('ErpGroupSponsorSkuImgs') -> where($map2) -> column('img_url');
        }
        $info['pic1'] = implode(',',$sku_img_1);
        $info['pic2'] = implode(',',$sku_img_2);

        if ($this->request->isPost()) {
            //数据接收
            $data = $this->request->post('', null, 'trim');
            if(!isset($data['pic1'])|| empty($data['pic1'])) $this->error('请上传商品缩略图');
//            if(!isset($data['pic2'])|| empty($data['pic2'])) $this->error('请上传商品详情图');
            $user_id    = intval(isset($data["user_id"]) ? $data["user_id"] : 1);
            $group_sid          = $info['group_sid'];
            $store_id           = $info['store_id'];
            $sku_id             = $info['sku_id'];
            $show_price         = strval(isset($data['show_price']) ? $data['show_price'] : '');
            $limit_num          = intval(isset($data['limit_num']) ? $data['limit_num'] : 0);
            $sorts              = intval(isset($data['sorts']) ? $data['sorts'] : 100);
            $sp_status          = intval(isset($data['sp_status']) ? $data['sp_status'] : 1);
            $tries              = intval(isset($data['tries']) ? $data['tries'] : 0);
            $sum_num            = intval(isset($data['sum_num']) ? $data['sum_num'] : 0);
            $dj_num             = intval(isset($data['dj_num']) ? $data['dj_num'] : $info['dj_num']);

            //数据验证
            $Validate = validate('GroupSponsor', 'validate');
            if( !$Validate -> scene('group_sponsor_add_sku') -> check($data) ){
                $this->error($Validate -> getError());
            }
            //验证数量   是否不存在   不存在0
            //验证数量   是否不存在   存在最低值
            $available_num = $this->get_sku($store_id,$sku_id,2);
            if($available_num['data'] < $sum_num){
                $this->error('参与团购总库存数超过仓库已有总数,最大参团数为'.$available_num['data']);
            }
            //团购总库存必出大于等于可使用数量
            if(!empty($info) && !is_null($info['ksy_num'])){
                $num = $sum_num - ($info['sum_num'] - $info['ksy_num']);
                if($num < 0){
                    $this->error('参与团购总库存数必须大于等于'.($info['sum_num'] - $info['ksy_num']).'个');
                }else{
                    $ksy_num = $num;
                }
            }else{}
            //当禁用是，检查已使用的数量，已使用的sku无法禁用
            if($sp_status < 1){
                if(!empty($info) && !is_null($info['ksy_num'])){
                    if($info['ksy_num'] < $info['sum_num']){
                        $this->error('该商品已参与团购活动，不可禁用！');
                    }
                }
            }
            //图片上传阿里云
            $data_list = [];
            if($data['pic1']){
                $pic_arr = explode(',', $data['pic1']);
                foreach ($pic_arr as $key => $value) {
                    if(strpos($value,'.aliyuncs.com') !== false){
                        //查找已有表数据
                        $have = model('ErpGroupSponsorSkuImgs')->where('img_url',$value)->find();
                        $data_list[] = [
                            'group_sid' => $group_sid,
                            'group_skuid' => $id,
                            'type' => 1,
                            'sku_id' => $sku_id,
                            'img_url' => $value,
                            'width'	=> $have['width'],
                            'height'	=> $have['height'],
                            'create_time' => time(),
                            'update_time' => time(),
                        ];
                    }else{
                        if($value != ''  && strpos($value,'groupsponsor/'.$group_sid.'/') ==false){
                            $rel_logo_pic = get_aliyun_pic_path($value,'groupsponsor/'.$group_sid.'/');
                            if($rel_logo_pic['code'] != 200) $this->error('图片上传失败');
                            $img_url  = $rel_logo_pic['data']['info']['url'];
                            //获取本地附件信息
                            $attachment_info = model('admin/Attachment') -> find($value);
                            $data_list[] = [
                                'group_sid' => $group_sid,
                                'group_skuid' => $id,
                                'type' => 1,
                                'sku_id' => $sku_id,
                                'img_url' => $img_url,
                                'width'	=> $attachment_info['width'],
                                'height'	=> $attachment_info['height'],
                                'create_time' => time(),
                                'update_time' => time(),
                            ];
                        }
                    }
                }
            }
            if($data['pic2']){
                $pic_arr = explode(',', $data['pic2']);
                foreach ($pic_arr as $key => $value) {
                    if(strpos($value,'.aliyuncs.com') !== false){
                        //查找已有表数据
                        $have = model('ErpGroupSponsorSkuImgs')->where('img_url',$value)->find();
                        $data_list[] = [
                            'group_sid' => $group_sid,
                            'group_skuid' => $id,
                            'type' => 2,
                            'sku_id' => $sku_id,
                            'img_url' => $value,
                            'width'	=> $have['width'],
                            'height'	=> $have['height'],
                            'create_time' => time(),
                            'update_time' => time(),
                        ];
                    }else{
                        if($value != ''  && strpos($value,'groupsponsor/'.$group_sid.'/') ==false){
                            $rel_logo_pic = get_aliyun_pic_path($value,'groupsponsor/'.$group_sid.'/');
                            if($rel_logo_pic['code'] != 200) $this->error('图片上传失败');
                            $img_url  = $rel_logo_pic['data']['info']['url'];
                            //获取本地附件信息
                            $attachment_info = model('admin/Attachment') -> find($value);
                            $data_list[] = [
                                'group_sid' => $group_sid,
                                'group_skuid' => $id,
                                'type' => 2,
                                'sku_id' => $sku_id,
                                'img_url' => $img_url,
                                'width'	=> $attachment_info['width'],
                                'height'	=> $attachment_info['height'],
                                'create_time' => time(),
                                'update_time' => time(),
                            ];
                        }
                    }
                }
            }

            $rel = controller('GroupSponsorlogic', 'logic') -> edit_goods($user_id, $id, $group_sid, $store_id, $sku_id, $show_price, $limit_num, $sorts, $sp_status, $tries, $sum_num, $dj_num, $ksy_num, $data_list);

            if($rel['code'] == 200){
                $this->success('编辑成功','', '_parent_reload');
            }else{
                $this->error($rel['message']);
            }
        }
        //获取筛选
        $map = $this->getMap();
        $map = [];
        $sku_info = $this->get_sku($info['store_id'],$info['sku_id'],1);
        if($info['store_id'] > 0){
            $store_arr = model('ErpStore')->where('id','=',$info['store_id'])->order('create_time asc') -> column('title');
            $store = implode(',',$store_arr);
        }else{
            $store = '全店通用';
        }
        if(!empty($sku_info)){
            $sku = '<pre><strong>';
            $sku .= '参与团购商品详情'.'<br/>';
            $sku .= '<br/>';
            $sku .= '参与门店：'.$store.'<br/>';
            $sku .= '商品名称：'.$sku_info['goods_name'].'<br/>';
            $sku .= '商品规格：'.$sku_info['goods_specifications'].'<br/>';
            $sku .= '进货价格：'.$sku_info['price'].' (￥)<br/>';
            $sku .= '库存数量：'.$sku_info['available_num'].'<br/>';
            $sku .= '</strong></pre>';
        }else{
            $sku = '<pre>暂无参与团购商品详情，请返回列表重试或者联系网站管理员！</pre>';
        }
        return ZBuilder::make('form')
            ->setPageTitle('新增团购商品') // 设置页面标题
            ->setPageTips($sku)
            ->addImages_oss('pic1', '产品缩略图', '', '', '', '', '', ['size' => '500,500'])
            ->addImages_oss('pic2', '产品详情图', '', '', '', '', '', ['size' => '500,500'])
            ->addFormItems([ // 批量添加表单项
                ['text','show_price', '展示价格'],
                //['number','limit_num', '限购数量','',1],
                //['number','tries', '购买次数限制','',1],
                ['text','sum_num', '参与团购总库存数'],
                ['text','sorts', '排序','',100],
                ['radio', 'sp_status', '', '', ['不可用', '可用'], 1]
            ])
            ->addHidden('group_sid')
            ->addHidden('limit_num',1)
            ->addHidden('tries',1)
            ->setFormData($info)
            ->fetch();
    }

    public function buyers($id='',$sku_id='')
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);
        if ($id === null) $this->error('缺少参数');
        if ($sku_id === null) $this->error('缺少参数');
        //获取筛选
        $map = $this->getMap();
        $map['sponsor_id'] = $id;
        $map['sku_id'] = $sku_id;
        //数据获取
        $data = input();
        //数据列表
        $data_list = model('ErpGroupTuxedo', 'model')
            -> alias('c')
            -> leftJoin('xm_uc_member u','c.uid = u.uid')
            -> field(['c.*','u.nick_name'])
            -> where($map)
            -> order('id asc')
            -> paginate();
        return ZBuilder::make('table')
            ->setPageTitle('参与团购参与人管理') // 设置页面标题
            ->setPrimaryKey('id') // 设置主键名为id
            ->setTableName('erp_group_tuxedo') // 设置数据表名
            ->addColumns([ // 批量添加列
                ['ct_status', '参团状态', 'status', '', [1 => '参团中:warning',2=>'组团成功:success','-1'=>'失败:danger']],
                ['sponsor_id', '团购id'],
                ['order_id', '订单id'],
                ['nick_name', '参与人', 'link', url('user_center/index/details', ['uid' => '__uid__']), '_blank', 'pop'],
                ['create_time', '购买时间', 'datetime'],
            ])
            ->setRowList($data_list) // 设置表格数据
            ->fetch(); // 渲染页面
    }

    /**
     * 团购获取sku数据
     *
     * @param string $store_id      门店id(当门店id=0时，全店通用)
     * @param bool $sku_id          商品sku_id
     * @param bool $type            使用场景（1:获取门店下全部商品数据并计算数量（包括全门店） ；2:添加/编辑商品使用计算最大参团数(针对门店不存在sku情况)）
     * @return array|mixed|\think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function get_sku($store_id='',$sku_id=false,$type=false)
    {
        $map = $this->getMap();
        $map = [];
        $map[] = ['n.sku_status','=',1];
        if($sku_id){
            $map[] = ['n.sku_id','=',$sku_id];
        }

        if($store_id > 0){
            //单门店
            $map[] = ['s.store_id','=',$store_id];
        }
        $data_lists = model('ErpStoreWarehouse')
            ->alias('s')
            ->rightJoin('xm_erp_warehouse w', 's.warehouse_id = w.id and w.type = 1')
            ->leftJoin('xm_erp_goods_warehouse_stock_num n', 's.warehouse_id = n.warehouse_id')
            ->leftJoin('xm_erp_goods_sku u', 'u.id = n.sku_id and u.goods_id = n.goods_id ')
            ->field('n.id,n.sku_id,n.available_num,n.price,u.*')
            ->where($map)
            ->select();

        //数组整理合并同类项
        $data_arr = [];
        if(!empty($data_lists)){
            foreach ($data_lists as $k=>$v){
                if(!isset($data_arr[$v['sku_id']])){
                    $data_arr[$v['sku_id']] = $v;
                }else{
                    //全店通用  区所有门店商品最小值
                    if($data_arr[$v['sku_id']]['available_num'] > $v['available_num']){
                        $data_arr[$v['sku_id']]['available_num'] = $v['available_num'];
                    }
                }
            }
            if($sku_id){
                if($type == 1){
                    //获取门店下商品sku_id（数据整理）
                    if(!empty($data_arr[$sku_id])){
                        $data_list = $data_arr[$sku_id];
                    }else{
                        $data_list = [];
                    }
                }elseif ($type == 2){
                    //获取门店下商品sku 并校验最大参团数（全门店下，包含门店为null情况）
                    $list_store = model('ErpStore')->order('create_time asc') -> column('id');
                    if($list_store && $store_id == 0){
                        foreach ($list_store as $k => $v){
                            $map1 = [];
                            $map1[] = ['n.sku_id','=',$sku_id];
                            $map1[] = ['s.store_id','=',$v];
                            $is_have = model('ErpStoreWarehouse')
                                ->alias('s')
                                ->rightJoin('xm_erp_warehouse w', 's.warehouse_id = w.id and w.type = 1')
                                ->leftJoin('xm_erp_goods_warehouse_stock_num n', 's.warehouse_id = n.warehouse_id')
                                ->field('n.id,w.*')
                                ->where($map1)
                                ->find();
                            unset($map1);
                            if(!$is_have || empty($is_have) || is_null($is_have)){
                                //门店下商品为空则直接 最大参团数为0
                                $data_list = [];
                                $data_list['code'] = '1'; //判断状态
                                $data_list['msg'] = '请求成功231'; //回传信息
                                $data_list['data'] = 0;
                                return $data_list;
                            }else{
                                //门店下商品各门店都存在，去最小值
                                $data_list = [];
                                $data_list['code'] = '1'; //判断状态
                                $data_list['msg'] = '请求成功'; //回传信息
                                $data_list['data'] = $data_arr[$sku_id]['available_num'];
                            }
                        }
                    }elseif ($list_store && $store_id > 0){
                        //门店下商品各门店都存在，去最小值
                        $data_list = [];
                        $data_list['code'] = '1'; //判断状态
                        $data_list['msg'] = '请求成功'; //回传信息
                        $data_list['data'] = $data_arr[$sku_id]['available_num'];
                    }else{
                        //门店为存在 最大参团数为各门店中最少
                        $data_list = [];
                        $data_list['code'] = '1'; //判断状态
                        $data_list['msg'] = '请求成功'; //回传信息
                        $data_list['data'] = 0;
                    }
                }else{
                    //获取门店下商品sku对应的最大参团数量（取各门店中库存最小数）
                    $data_list = [];
                    $data_list['code'] = '1'; //判断状态
                    $data_list['msg'] = '请求成功'; //回传信息
                    $data_list['data'] = $data_arr[$sku_id]['available_num'];
                }
                return $data_list;
            }else{
                //列表返回展示数据（select联动）
                $data_list = [];
                if(!empty($data_arr)){
                    foreach ($data_arr as $key=>$value){
                        $data_list['code'] = '1'; //判断状态
                        $data_list['msg'] = '请求成功'; //回传信息
                        if($store_id > 0){
                            $data_list['list'][] = ['key' => $value['sku_id'], 'value' => $value['goods_id'].' '.$value['goods_name'].' ---[ 规格：'.$value['goods_specifications'].' | 价格：'.$value['price'].' | 门店下总库存：'.$value['available_num'].' ]'];
                        }else{
                            $data_list['list'][] = ['key' => $value['sku_id'], 'value' => $value['goods_id'].' '.$value['goods_name'].' ---[ 规格：'.$value['goods_specifications'].' | 价格：'.$value['price'].']'];
                        }
                    }
                }else{
                    $data_list['code'] = '1'; //判断状态
                    $data_list['msg'] = '请求成功'; //回传信息
                    $data_list['list'][] = ['key' => 0, 'value' => '暂无数据'];
                }
            }
        }else{
            //门店查询数据为空时
            $data_list['code'] = '1'; //判断状态
            $data_list['msg'] = '请求成功'; //回传信息
            $data_list['list'][] = ['key' => 0, 'value' => '暂无数据'];
        }
        return json($data_list);
    }

    public function get_sku_info($store_id,$sku_id)
    {
        if(empty($store_id)  || empty($sku_id)){
            return '暂无数据';
        }
        $map = $this->getMap();
        $map = [];
        $map[] = ['n.sku_status','=',1];
        $map[] = ['n.sku_id','=',$sku_id];
        //单门店
        $map[] = ['s.store_id','=',$store_id];
        $data_lists = model('ErpStoreWarehouse')
            ->alias('s')
            ->rightJoin('xm_erp_warehouse w', 's.warehouse_id = w.id and w.type = 1')
            ->leftJoin('xm_erp_goods_warehouse_stock_num n', 's.warehouse_id = n.warehouse_id')
            ->leftJoin('xm_erp_goods_sku u', 'u.id = n.sku_id and u.goods_id = n.goods_id ')
            ->field('n.id,n.sku_id,n.stock_num,n.frozen_num,n.available_num')
            ->where($map)
            ->find();
        if($data_lists &&  !empty($data_lists)){
            $data_list = '库存总数[<strong style="color: darkred">'.$data_lists['stock_num'].'</strong>]/<br/>冻结数[<strong style="color: darkred">'.$data_lists['frozen_num'].'</strong>]/<br/>可操作数[<strong style="color: darkred">'.$data_lists['available_num'].'</strong>]';
            return $data_list;
        }else{
            return '';
        }

    }

}
